const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ManifestPlugin = require('webpack-manifest-plugin');
const Visualizer = require('webpack-visualizer-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const theme = require('./theme');
const CleanCSSPlugin = require('less-plugin-clean-css');
const MinifyPlugin = require("babel-minify-webpack-plugin");
//const CompressionPlugin = require("compression-webpack-plugin");

const extractCSS = new ExtractTextPlugin({
    filename: "[name]css.[contenthash].css",
    allChunks:true
});
const extractAntdLESS = new ExtractTextPlugin({
    filename: "[name]antdLess.[contenthash].css",
    allChunks:false
});
// const extractLESS = new ExtractTextPlugin({
//     filename: "[name]Less.[contenthash].css",
//     allChunks:false
// });

module.exports = {
    entry: {
        index:'./src/index.js',
        vendor: [
            'react',
            'react-dom',
            'dva',
            'dva-loading',
            'react-router-dom',
            'AlloyTouch',
            'css3transform'
        ]
    },
    output: {
        filename: "[name].[chunkhash].js",
        path: path.resolve(__dirname, 'dist'),
        chunkFilename:"[id].[name].[chunkhash].js",
        // publicPath: "http://testbbc.leimingtech.com/dist/",
        publicPath: "/",
    },
    devtool: false,
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [
                    'babel-loader'
                ],
                include: path.resolve('src')
            },
            {
                test: /\.css$/,
                use: extractCSS.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 2,
                                minimize: true
                            }
                        },
                        {
                            loader:'resolve-url-loader'
                        },
                        'postcss-loader'
                    ]
                })
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.less$/,
                include: [
                    // path.resolve(__dirname, "src"),
                    path.resolve(__dirname, "node_modules")
                ],
                use: extractAntdLESS.extract({
                    fallback: 'style-loader',
                    use: [
                       // { loader: "file-loader" },
                        {
                            loader: 'postcss-loader'
                        },
                        {
                            loader: "less-loader",
                            options: {
                                modifyVars: theme
                            }
                        }
                    ]
                })


                // use: [
                //     {
                //         loader: 'style-loader/url'
                //     },
                //     { loader: "file-loader" },
                //     {
                //         loader: 'postcss-loader'
                //     },
                //     {
                //         loader: "less-loader",
                //         options: {
                //             modifyVars: theme
                //         }
                //     }
                // ]
            },


            {
                test: /\.less$/,
                include: [
                    path.resolve(__dirname, "src")
                ],
                use:
                    [
                        { loader: "style-loader", options:{ convertToAbsoluteUrls: true } },

                        // { loader: "file-loader" },
                        // {
                        //     loader: "extract-loader",
                        //     // options: {
                        //     //     publicPath: "../",
                        //     // }
                        // },
                        {
                            loader: "css-loader",
                            options: {
                                modules: true,
                                localIdentName: '[name]_[local][hash:base64:5]',
                                importLoaders: 3,
                                sourceMap: false,
                                import:true
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                //  modules: true,
                                //  localIdentName: '[name]_[local][hash:base64:5]',
                                //  importLoaders: 1,
                                sourceMap: false,
                                //   import:true,
                                //   strictMath: true,
                                //   noIeCompat: true
                            }
                        },
                        {
                            loader:'resolve-url-loader'
                        },
                        {
                            loader: "less-loader",
                            options: {
                                modules: true,
                                localIdentName: '[name]_[local][hash:base64:5]',
                                importLoaders: 0,
                                sourceMap: false,
                                import:true,
                                strictMath: true,
                                noIeCompat: true
                            }
                        }
                    ]
                // use: extractLESS.extract(
                //     {
                //    fallback:[
                //        { loader: "style-loader" }
                //    ] ,
                //    use:
                //         [
                //             { loader: "file-loader" },
                //         {
                //             loader: "extract-loader",
                //             // options: {
                //             //     publicPath: "../",
                //             // }
                //         },
                //         {
                //             loader: "css-loader",
                //             options: {
                //                modules: true,
                //                 localIdentName: '[name]_[local][hash:base64:5]',
                //                 importLoaders: 3,
                //                 sourceMap: true,
                //                 import:true
                //             }
                //         },
                //         {
                //             loader:'resolve-url-loader'
                //         },
                //         {
                //             loader: "less-loader",
                //             options: {
                //                 modules: true,
                //                 localIdentName: '[name]_[local][hash:base64:5]',
                //                 importLoaders: 1,
                //                 sourceMap: true,
                //                 import:true,
                //                 strictMath: true,
                //                 noIeCompat: true
                //             }
                //         },
                //         {
                //             loader: 'postcss-loader'
                //         }
                //     ]
                //  }
                // )

            },
            // {
            //     test: /\.less$/,
            //     include: [
            //         path.resolve(__dirname, "src")
            //     ],
            //     use: extractLESS.extract({
            //         fallback: 'style-loader',
            //         use: [
            //             // {
            //             //     loader: "style-loader"
            //             // },
            //             {
            //                 loader: "css-loader",
            //                 options: {
            //                     modules: true,
            //                     localIdentName: '[name]_[local][hash:base64:5]',
            //                     importLoaders: 3,
            //                     sourceMap: false,
            //                     import:true,
            //                     minimize: true //css压缩
            //                 }
            //             },
            //             {
            //                 loader:'resolve-url-loader'
            //             },
            //             {
            //                 loader: "less-loader",
            //                 options: {
            //                     modules: true,
            //                     localIdentName: '[name]_[local][hash:base64:5]',
            //                     importLoaders: 1,
            //                     sourceMap: false,
            //                     import:true,
            //                     minimize: true, //css压缩
            //                   //  strictMath: true,
            //                   //  noIeCompat: true
            //                     // lessPlugins: [
            //                     //     new CleanCSSPlugin({ advanced: true })
            //                     // ]
            //                 }
            //             },
            //             {
            //                 loader: 'postcss-loader'
            //             }
            //         ]
            //     })
            //
            // },
            {
                test: /\.(png|jpg|gif|eot|ttf|woff|woff2)$/,
                loader: 'url-loader',
                options: {
                    limit: 10000
                }
            },
            {
                test: /\.svg$/i,
                use: 'svg-sprite-loader',
                include: [
                    require.resolve('antd-mobile').replace(/warn\.js$/, ''), // 1. 属于 antd-mobile 内置 svg 文件
                    path.resolve(__dirname, 'src'), // 2. 自己私人的 svg 存放目录
                ]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title:"dva",
            template: 'src/index.html',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
            chunksSortMode:'dependency'
        }),
        // new webpack.optimize.AggressiveSplittingPlugin(
        //     {
        //         minSize: 30000, // 字节，分割点。默认：30720
        //         maxSize: 50000, // 字节，每个文件最大字节。默认：51200
        //         chunkOverhead: 0, // 默认：0
        //         entryChunkMultiplicator: 1, // 默认：1
        //     }
        // ),
        // new ExtractTextPlugin({
        //     filename: "[name].[contenthash].css"
        //     // allChunks:true
        // }),
        extractCSS,
        extractAntdLESS,
      //  extractLESS,
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
           // filename: "vendor.js",
            // (给 chunk 一个不同的名字)

            minChunks: Infinity,
            // (随着 entry chunk 越来越多，
            // 这个配置保证没其它的模块会打包进 vendor chunk)
        }),
        // new webpack.optimize.CommonsChunkPlugin({
        //     name: "runtime",
        //     // filename: "vendor.js",
        //     // (给 chunk 一个不同的名字)
        //
        //     minChunks: Infinity,
        //     chunks: ['vendor']
        //     // (随着 entry chunk 越来越多，
        //     // 这个配置保证没其它的模块会打包进 vendor chunk)
        // }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'index',
            //  names: [""],
            //  filename: "commom.js",
            children: true,
           // minChunks: 3,
            minChunks: function (module,count) {
                //console.log(module.resource,`引用次数${count}`);
                //"有正在处理文件" + "这个文件是 .js 后缀" + "这个文件是在 node_modules 中"
                return (
                    module.resource &&
                    /(md5|doSign|NavTopBar|MyScroll)\.js$/.test(module.resource) &&
                    module.resource.indexOf(path.join(__dirname, './src')) === 0
                )
            },
            //deepChildren: true,
            async: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest'
        }),
      //  new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"',
                BABEL_ENV:JSON.stringify("production")
            }
        }),
        new Visualizer({
            filename: './statistics.html'
        }),
        new webpack.HashedModuleIdsPlugin(),
        new ManifestPlugin(),
        new UglifyJsPlugin(
            {
                uglifyOptions: {
                    ie8: false,
                    ecma: 8,
                   // parse: {...options},
                   //  mangle: {
                   //      ...options,
                   //      properties: {
                   //          // mangle property options
                   //      }
                   //  },
                   //  output: {
                   //      comments: false,
                   //      beautify: false,
                   //      ...options
                   //  },
                    comments: false,
                    compress: {
                        warnings: false,
                        drop_debugger: true,
                        drop_console: true
                    },
                    warnings: false
                }
            }
        ),
      //  new MinifyPlugin()
        //new webpack.optimize.DedupePlugin()
        new webpack.NamedModulesPlugin()
    ]
};